<?php

namespace app\mp\admin;

use app\common\service\Board;
use app\common\service\OrderUser;
use app\common\service\Sku as SkuService;
use app\common\service\Order as OrderService;
use app\system\admin\Admin;
use think\Container;
use think\Db;

/**
 * 现场看板
 * @author huanghuixiang
 * @date  2022/11/29
 *
 */
class LocalBoard extends Admin
{

    public function index()
    {

        $action=$this->request->param("action");
        $addressId= $this->request->param('address_id/d', 1);
        $address_name=db('board_address')->field('address_name')->where(['id'=>$addressId])->find();
        if($action=='refreshSearchLabels'){
            $labelstr = $this->_showSearchLabels();
            $result = [
                'code' => 0, 'msg' => 'success','labelstr'=>$labelstr,
            ];
            return json($result);
        }
        if ($this->request->isAjax()) {
            $address_id = $this->request->param('address_id','1');
            $address_id=$address_id !=''?$address_id:1;
            $BoardService=new Board();
            //获取看板数据
            $data=$BoardService->getBoardData($address_id);
            return json($data);
        }

        $menuList=db('board b')
            ->field('b.address_id,ba.address_name')
            ->join('board_address ba','b.address_id=ba.id','left')
            ->where('b.address_id >0')
            ->group('b.address_id')->order('b.id asc ')->select();

        $addressList=db('board_address')->field('id,address_name')->select();
        $new_list=[];
        foreach ($addressList as $key=>$val){
            $new_list[$val['id']]=$val['address_name'];
        }

        $assign = [
            'new_list' => [0 => '请选择'] + $new_list,
            'menuList' => $menuList,
            'address_id' => $addressId,
            'address_name' => $address_name['address_name'],
        ];
        return $this->assign($assign)->fetch();
    }


    public function shareVideo(){

        $assign = [
        ];
        return $this->assign($assign)->fetch();
    }
    //添加标签
    public function addSmallLabel(){
        $address_id=$this->request->param('address_id/s');
        $lable_ID=$this->request->param('lable_ID');
         if(!empty($lable_ID)){
             $saveInfo=$this->request->param();
             $data2['break_code_up']=$saveInfo['break_code_up'];
             $data2['order_type_up']=$saveInfo['order_type_up'];
             $data2['speed_seting']=$saveInfo['speed_seting'];

             $resault=db('board')->where(['id'=>$saveInfo['lable_ID']])->update($data2);
             if($resault){
                 return $this->success('保存成功', '');
             }else{
                 return $this->error('保存失败', '');
             }

         }
        if ($this->request->isAjax() && empty($lable_ID)) {
            $id=$this->request->param('id/s');
            $info=db('board b')->field('b.id,b.speed_seting,b.order_type_up,b.break_code_up')->where(['id'=>$id])->find();
            $data['code'] = 0;
            $data['msg'] = '';
            $data['data'] = $info;
            return  json($data);
        }
        $lable_list=db('board b')->field('b.id,b.address_id,b.label_name,b.speed_seting,b.order_type_up,b.break_code_up')->where(['b.address_id'=>$address_id,'show_status'=>1])->select();
        $new_list=[];
        foreach ($lable_list as $key=>$val){
            $new_list[$val['id']]=$val['label_name'];
        }
        if(count($new_list)>1){
            $new_list=[""=>""]+$new_list;
        }
        $assign = [
            'info'=>$lable_list[0],
            'address_id'=>$address_id,
            'new_list'=>$new_list
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 设置配置看板
     * @author  huanghuixiang
     * @date 2022/11/23 14:36
     */
    public function boardList(){

        $useAction=$this->request->param('use_action/s');
        switch ($useAction) {
            case "edit_search_label": //创建与编辑搜索标签
                return $this->addSearchLabel();
                break;
            case"del_search_label": //删除搜索标签
                return $this->delSearchLabel();
                break;
        }
        if ($this->request->isAjax()) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $name    = $this->request->param('name/s');
            $color    = $this->request->param('color/s');
            $materialSku    = $this->request->param('material_sku/s');
            $sku    = $this->request->param('sku/s');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $supplier    = $this->request->param('supplier/s');
            //本地订单状态
            $local_client_status=[0=>'']+config('mimo.local_client_status');

            if ($supplier != '') {
                $where[] = ['b.supplier', 'like', "%{$supplier}%"];
            }
            if ($name != '') {
                $where[] = ['label_name', 'like', "%{$name}%"];
            }
            if ($color != '') {
                $where[] = ['b.color', 'like', "%{$color}%"];
            }
            if ($materialSku != '') {
                $where[] = ['b.material_sku', '=', $materialSku];
            }
            $marerialType=['全部','面料','辅料'];//物料类型
            $materialStatus=[1=>'未采购',2=>'采购中',3=>'换料中',4=>'已到料',5=>'未批色',6=>'批色不通过',7=>'已批色',13=>'未发货',14=>'已发货',8=>'批色已齐套',9=>'批色未齐套',10=>'采购未齐套',11=>'采购已齐套',
                15=>'发货未齐套',16=>'发货已齐套',12=>'可裁剪',17=>'已裁床/已车缝/已后整',18=>'已打标',19=>'待退审',20=>'占用已出库']; //搜索物料状态
            $factoryKV =[0=>'未分厂']+getFactoryKV(true);
            $orderTypeArr=[''=>'全部','normal'=>'返单','new'=>'首单','emergent'=>'紧急单','my_first'=>'（奖励）第一次做（不含尾货）','my_return_first'=>'初返'];
            $rolelist=db("system_role")->column("name","id");
            $systemUserKV = getSystemUserKV(null);
            $field="b.*,ba.address_name";
            $order = 'ba.address_name desc,b.order asc,b.id asc';

            $data['data'] = db('board b')->field($field)
                ->join('board_address ba','b.address_id=ba.id','left')
                ->where($where)->page($page)->limit($limit)->order($order)->select();

            foreach ($data['data'] as $k => &$v) {
                $v['materialtype_str']=$marerialType[$v['search_materal_type']];
                $searchMaterialStatus=$v['search_data_status']!='' ? explode(',',$v['search_data_status']) : [];
                $search_marerialStatus=[];
                foreach ($searchMaterialStatus as $key => $value) {
                    $search_marerialStatus[]= arrayGet($materialStatus, $value, '');
                }
                $marerialStatus_str = implode(",", $search_marerialStatus);
                $v['marerialStatus_str'] =$marerialStatus_str;
                $v['order_type']=$orderTypeArr[$v['order_type']];
                $v['admin_user']=$systemUserKV[$v['admin_id']];
                $v['order_status']=$local_client_status[$v['order_status']];
                $v['shipment_day']=$v['shipment_day']=='' ? "全部" : $this->_getShipmentDay($v['shipment_day']);
                $v['factory_ids_str']=$v['factory_ids']=='' ? "" : $this->_getIdstrNames($v['factory_ids'],$factoryKV);
                $v['visit_roles_str']=$v['visit_role_ids']=='' ? '' : $this->_getIdstrNames($v['visit_role_ids'],$rolelist);
                $v['visit_admins_str']=$v['visit_admin_ids']=='' ? '' : $this->_getIdstrNames($v['visit_admin_ids'],$systemUserKV);
            }
            $data['marerialType']=$marerialType;
            $data['count'] = db('board')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [];
        return $this->assign($assign)->fetch();
    }

    /**
     *删除搜索标签
     */
    public function delSearchLabel(){
        $id  = $this->request->param('id/d', 0);
        db('board')->where('id', $id)->delete();
        $data['code'] = 1;
        $data['msg'] = 'success';
        return json($data);
    }

    /**
     * 增加自定义搜索标签
     */
    public function addSearchLabel(){
        if ($this->request->isPost()) {
            $search_label_id  = $this->request->param('id/d', 0);
            $postData = $this->request->post();

            unset($postData['storehouse_id']);
            if(!empty($postData['empty_factory_order'])){
                $postData['factory_ids']='0,'.$postData['factory_ids'];
                unset($postData['empty_factory_order']);
            }

            if(empty($search_label_id)){
                //一个展示地址 不能超过4个标签
                $address_count= db('board')->where(['address_id'=>$postData['address_id']])->count();
                if($address_count>=4){
                    return $this->error('该展示地址下超过4个标签！不能新增！');
                }
                $postData['admin_id'] =ADMIN_ID;
                $postData['create_time'] = $postData['update_time'] = time();
                $id = db('board')->insertGetId($postData);
                if (!$id) {
                    return $this->error('保存失败');
                }
                return $this->success('保存成功', '');
            }else{  //修改搜索标签操作
                $savedata=[];
                if(isset($postData['show_status'])){
                    $savedata['show_status']=$postData['show_status'];
                }
                if(empty($postData['label_color'])){
                    unset($postData['label_color']);
                }
                $savedata=$postData;
                $savedata['admin_id']=ADMIN_ID;
                $savedata['update_time']=time();
                db('board')->where('id', $search_label_id)->update($savedata);
                return $this->success('保存成功', '');
            }
        }
        $id  = $this->request->param('id/d', 0);
        $labelInfo=db("board")->find($id);
        $assign = [
            'unitKV' => getUnitKV(),
        ];

        $roles=db("system_role")->field("name,id as value")->select();
        $roleNameKey=array_column($roles,'name','id');
        $assign['role_names']=$roleNameKey;

        //可访问的角色
        $use_roles=$labelInfo['visit_role_ids']!='' ? explode(',',$labelInfo['visit_role_ids']) : [];
        $roleArrs=[];
        foreach ($roles as $key=>$txt) {
            $roleArr = ['name' => $txt['name'], 'value' => $txt['value']];
            if(is_array($use_roles) && in_array($txt['value'],$use_roles)){
                $roleArr['selected']=true;
            }
            $roleArrs[]=$roleArr;
        }

        $assign['visit_role_ids']=$roleArrs;


        //搜索工厂
        $factoryKV =[0=>'没有分工厂(未分厂)'] + getFactoryKV(false);
        $use_factoryids=$labelInfo['factory_ids']!='' ? explode(',',$labelInfo['factory_ids']) : [];
        foreach ($factoryKV as $key=>$txt) {
            $factoryArr = ['name' => $txt, 'value' => $key];
            if(is_array($use_factoryids) && in_array($key,$use_factoryids)){
                $factoryArr['selected']=true;
            }
            $factoryList[]=$factoryArr;
        }
        $assign['factorylist']=$factoryList;

        //搜索小组
        $use_factoryids=$labelInfo['group_ids']!='' ? explode(',',$labelInfo['group_ids']) : [];
        $assign['factoryAll']= $this->_factorylist([], true, [],$use_factoryids);

        //-------可访问帐号 获取列表供选择
        $audit_users=$labelInfo['visit_admin_ids']!='' ? explode(',',$labelInfo['visit_admin_ids']) : [];
        $systemUserKV = getSystemUserKV(null);
        foreach ($systemUserKV as $key => $value) {
            $auditUser=$otherUser=['name'=>$value,'value'=>$key];
            if(is_array($audit_users) && in_array($key,$audit_users)){
                $auditUser['selected']=true;
            }
            $assign['visit_admin_ids'][]=$auditUser;
        }
        //展示地址
        $board_address=db("board_address")->field("id,address_name")->select();
        $addressList=[];
        foreach ($board_address as $value){
            $addressList[$value['id']]=$value['address_name'];
        }
        $assign['board_address']=['' => '请选择','-100'=>'+新增加地址'] +$addressList;

        //-------剩余出货天数  //剩余出货天数
        $day=['1'=>"1天",'2'=>"2天",'3'=>"3天",'4'=>"4天",'5'=>"5天",'6'=>"6天",'7'=>"7天"];
        $some_day=$labelInfo['shipment_day']!='' ? explode(',',$labelInfo['shipment_day']) : [];
        foreach ($day as $key => $value) {
            $shipmentDay=['name'=>$value,'value'=>$key];
            if(is_array($some_day) && in_array($key,$some_day)){
                $shipmentDay['selected']=true;
            }
            $assign['shipment_day'][]=$shipmentDay;
        }

        //------------------下拉联动 1级 2级菜单
        $firstMenus=db("system_menu")->where("pid=142")->column("title",'id');
        $secondMenus=db("system_menu")->where([['pid', 'in', array_keys($firstMenus)],['status','eq',1]])->field("id,pid,title")->select();
        $assign['storehouseKV'] = ['' => '请选择'] + $firstMenus;

        $secondMenuList=[];
        foreach ($secondMenus as $key=>$item){
            $secondMenuList[$item['pid']][$item['id']]=$item['title'];
        }
        $storeshelfMap = [];
        foreach ($firstMenus as $k => $v) {
            if ($k > 0)	$storeshelfMap[$k] = $secondMenuList[$k];
        }
        $assign['storeshelfMap'] = $storeshelfMap;
        $newMaterialStatus=[];
        $materialStatus=[1=>'未采购',2=>'采购中',3=>'换料中',4=>'已到料',5=>'未批色',6=>'批色不通过',7=>'已批色',13=>'未发货',14=>'已发货',8=>'批色已齐套',9=>'批色未齐套',10=>'采购未齐套',11=>'采购已齐套',
            15=>'发货未齐套',16=>'发货已齐套',12=>'可裁剪',17=>'已裁床/已车缝/已后整',18=>'已打标',19=>'待退审',20=>'占用已出库'];
        $use_material_status=$labelInfo['search_data_status']!='' ? explode(',',$labelInfo['search_data_status']) : [];
        foreach ($materialStatus as $key=>$txt){
            $otherUser=['name'=>$txt,'value'=>$key];
            if(is_array($use_material_status) && in_array($key,$use_material_status)){
                $otherUser['selected']=true;
            }
            $newMaterialStatus[]=$otherUser;
        }
        $search_materal_type=isset($labelInfo['search_materal_type']) ? $labelInfo['search_materal_type'] : ''; //搜索物料类型 默认显示面料
        $empty_factory_order= empty('factory_ids') || substr($labelInfo['factory_ids'],0,1)==0 ? 1 : 0;
        $bgcolor=empty($labelInfo['label_color']) ? '#009688' :$labelInfo['label_color'];

        if(!empty($labelInfo)){
            $labelInfo['search_history']= !empty($labelInfo['search_history'])?$labelInfo['search_history']:'today';
        }
        $assign['labelInfo']=$labelInfo;
        $assign['bgcolor']=$bgcolor;
        $assign['empty_factory_order']=$empty_factory_order;
        $assign['search_materal_type']=(int)$search_materal_type;
        $assign['materialStatus'] = $newMaterialStatus;

        //$assign['visit_role_ids']=$newMaterialStatus;
        $template = $this->request->param('template', 'edit_search_label');
        return $this->assign($assign)->fetch($template);
    }


    /**
     *  获取所有工厂信息
     *  $this->_factorylist([
     * 'ft_id' => $info['ft_id'],
     * 'ft_type' => 1,
     * 'group_id' => $info['group_id'],
     * ]),
     * @param $param
     * @return array
     */
    private function _factorylist($param, $xm_select = false, $parent_selected = [], $child_selected = [])
    {

        $where = [];
        if (isset($param['ft_type'])) {
            $where[] = ['ft.type', '=', $param['ft_type']];
        }
        $where[] = ['ft.status', '=', 1];
        $where[] = ['g.status', '=', 1];
        $factorylist = db('factory ft')
            ->field('ft.id as ft_id,ft.name as ft_name,ft.type as ft_type 
            ,g.id as group_id,g.name as group_name ,g.factory_id as group_factory_id
            ')
            ->join('wx_group g', 'g.factory_id=ft.id', 'left')
            ->where($where)
            ->select();
        $result = [];
        foreach ($factorylist as $k => $v) {
            if (isset($result[$v['ft_id']])) {
                continue;
            }
            $result[$v['ft_id']]['ft_id'] = $v['ft_id'];
            $result[$v['ft_id']]['ft_name'] = $v['ft_name'];
            $result[$v['ft_id']]['ft_type'] = $v['ft_type'];
            $result[$v['ft_id']]['selected'] = 0;
            if (isset($param['ft_id'])) {
                $v['ft_id'] == $param['ft_id'] && $result[$v['ft_id']]['selected'] = 1;
            }
            foreach ($factorylist as $k2 => $v2) {
                if ($v2['group_factory_id'] == $v['ft_id']) {
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_id'] = $v2['group_id'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_name'] = $v2['group_name'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 0;
                    if (isset($param['group_id'])) {
                        $v2['group_id'] == $param['group_id'] && $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 1;
                    }
                }
            }
        }
        if ($xm_select == true) {
            $factoryAll = [];
            foreach ($result as $k => $v) {
                $temp = [
                    'name' => $v['ft_name'],
                    'value' => -$v['ft_id'],
                    'children' => [],
                ];
                if (count($v['child']) > 0) {
                    foreach ($v['child'] as $k2 => $v2) {
                        $flag = false;
                        foreach ($child_selected as $ks => $vs) {
                            if ($v2['group_id'] == $vs) {
                                $flag = true;
                            }
                        }
                        $tempgrop = [
                            'name' => $v2['group_name'],
                            'value' => $v2['group_id'],
                            'selected' => $flag,
                        ];
                        $temp['children'][] = $tempgrop;
                    }
                }
                $factoryAll[] = $temp;
            }
            return $factoryAll;
        }
        return $result;
    }

    /**
     *转换剩余出货天数
     */
    private function _getShipmentDay($shipment_day_str){
        $shipment_day_list = explode(",", $shipment_day_str);
        if(count($shipment_day_list)>=2){
           $shipment_day=min($shipment_day_list).'~'. max($shipment_day_list).'天';
        }else{
           $shipment_day=min($shipment_day_list).'天';
        }
       return $shipment_day;
    }
    private function _getIdstrNames($strids,$idkeyArr){
        $search_marerialStatus=[];
        $stridsArr = explode(",", $strids);
        foreach ($stridsArr as $key => $value) {
            $search_marerialStatus[]= arrayGet($idkeyArr, $value, '');
        }
        $marerialStatus_str = implode(",", $search_marerialStatus);
        return $marerialStatus_str;
    }


    /**
     * 新增展示地址
     * @author  huanghuixiang
     * @date 2022/11/24 17:36
     */
    public function addAddress(){
        $address        = $this->request->param('address/s');
        if ($this->request->isPost() && !empty($address)) {
           $address_info=  db('board_address')->where(['address_name'=>$address])->find();

           if(!empty($address_info)){
               return $this->error('展示地址名字重复，请确认！');
           }
           $data['create_time']=time();
           $data['update_time']=time();
           $data['address_name']=$address;
           $res=db('board_address')->insert($data);
           if($res){
               return $this->success('新增加成功', '');
           }else{
               return $this->error('新增失败！');
           }

        }
        $assign = [
        ];
        return $this->assign($assign)->fetch();
    }
    //设置排序
    public function setBorad(){
        $id  = $this->request->param('id/s');
        $order  = $this->request->param('order/s');
        if(!empty($id) ){
            db('board')->where(['id'=>$id])->update(['order'=>$order]);
        }
        return $this->success('修改成功', '');
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $url = null, $data = '', $wait = 1, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ('' !== $url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : Container::get('url')->build($url);
        }

        $result = [
            'code' => 1,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        // 把跳转模板的渲染下沉，这样在 response_send 行为里通过getData()获得的数据是一致性的格式
        if ('html' == strtolower($type)) {
            $type = 'jump';
        }
        return json($result);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        $type = $this->getResponseType();
        if (is_null($url)) {
            $url = $this->app['request']->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ('' !== $url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app['url']->build($url);
        }

        $result = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        if ('html' == strtolower($type)) {
            $type = 'jump';
        }
        return json($result);
    }

}